package cn.lijiguo.concurrency.part1.ch06;

import java.time.Duration;
import java.time.Instant;

/**
 * ThreadService
 * 优雅的方式结束线程
 * @author lijiguo
 * @date 2019/12/13 16:17
 */
public class ThreadService {

    // 执行线程
    private Thread executeThread;

    // 结束标识
    private volatile boolean finished = false;

    public void execute(Runnable task) {
        executeThread = new Thread() {
            @Override
            public void run() {
                Thread runner = new Thread(task);
                // 将任务设置为守护线程
                // 如果执行线程结束，那么守护线程也会结束
                runner.setDaemon(true);
                runner.start();
                try {
                    runner.join();
                    finished = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        executeThread.start();
    }

    public void shutdown(long mills) {
        Instant start = Instant.now();
        while(!finished) {
            long executeTime = Duration.between(start, Instant.now()).toMillis();
            if (executeTime >= mills) {
                System.out.println("任务超时，需要结束");
                // 打断执行线程
                executeThread.interrupt();
                break;
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                System.out.println("执行线程被打断。。。");
                e.printStackTrace();
            }
        }

        this.finished = false;
    }
}
